import { ref, computed } from 'vue'

// 用户状态响应式变量
const user = ref(null)
const isAuthenticated = ref(false)
const isLoading = ref(false)

// 初始化用户状态
const initializeAuth = () => {
  const storedUser = getUserFromLocalStorage()
  if (storedUser) {
    user.value = storedUser
    isAuthenticated.value = true
  }
}

// 从本地存储获取用户信息
const getUserFromLocalStorage = () => {
  const userData = localStorage.getItem('user')
  return userData ? JSON.parse(userData) : null
}

// 将用户信息保存到本地存储
const saveUserToLocalStorage = (userData) => {
  localStorage.setItem('user', JSON.stringify(userData))
}

// 移除本地存储中的用户信息
const removeUserFromLocalStorage = () => {
  localStorage.removeItem('user')
  // 如果有记住我功能，这里可以保留用户信息
  const rememberMe = localStorage.getItem('rememberMe') === 'true'
  const username = localStorage.getItem('rememberedUsername')
  
  if (!rememberMe && username) {
    localStorage.removeItem('rememberedUsername')
  }
}

// 登录方法
const login = async (username, password, rememberMe = false) => {
  isLoading.value = true
  
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 模拟登录验证
    if (!username || !password) {
      throw new Error('用户名和密码不能为空')
    }
    
    // 创建用户对象
    const newUser = {
      id: Math.floor(Math.random() * 1000),
      username,
      name: `用户${username}`,
      email: `${username}@example.com`, // 模拟邮箱
      avatar: `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/200/200`,
      role: 'user',
      // 会员相关信息
      coins: 100, // 初始金币数量
      membership: {
        level: 1,
        points: 0,
        createdAt: new Date().toISOString()
      },
      // 用户拥有的宠物用品
      inventory: []
    }
    
    // 保存用户信息
    user.value = newUser
    isAuthenticated.value = true
    saveUserToLocalStorage(newUser)
    
    // 处理记住我功能
    if (rememberMe) {
      localStorage.setItem('rememberMe', 'true')
      localStorage.setItem('rememberedUsername', username)
    } else {
      localStorage.removeItem('rememberMe')
      localStorage.removeItem('rememberedUsername')
    }
    
    return newUser
  } catch (error) {
    console.error('登录失败:', error)
    throw error
  } finally {
    isLoading.value = false
  }
}

// 注册方法
const register = async (userData) => {
  const { username, email, password } = userData
  isLoading.value = true
  
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 简单验证
    if (!username || !email || !password) {
      throw new Error('请填写所有必填字段')
    }
    
    // 创建用户对象
    const newUser = {
      id: Math.floor(Math.random() * 1000),
      username,
      name: username,
      email,
      avatar: `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/200/200`,
      role: 'user',
      // 会员相关信息
      coins: 200, // 注册奖励金币
      membership: {
        level: 1,
        points: 0,
        createdAt: new Date().toISOString()
      },
      // 用户拥有的宠物用品
      inventory: []
    }
    
    // 保存用户信息
    user.value = newUser
    isAuthenticated.value = true
    saveUserToLocalStorage(newUser)
    
    return newUser
  } catch (error) {
    console.error('注册失败:', error)
    throw error
  } finally {
    isLoading.value = false
  }
}

// 退出登录方法
const logout = () => {
  user.value = null
  isAuthenticated.value = false
  removeUserFromLocalStorage()
}

// 获取用户金币数量
const getUserCoins = () => {
  return user.value?.coins || 0
}

// 增加用户金币
const addCoins = (amount) => {
  if (!user.value) {
    throw new Error('用户未登录')
  }
  
  user.value.coins = (user.value.coins || 0) + amount
  saveUserToLocalStorage(user.value)
  return user.value.coins
}

// 减少用户金币
const spendCoins = (amount) => {
  if (!user.value) {
    throw new Error('用户未登录')
  }
  
  if ((user.value.coins || 0) < amount) {
    throw new Error('金币不足')
  }
  
  user.value.coins -= amount
  saveUserToLocalStorage(user.value)
  return user.value.coins
}

// 获取用户物品库存
const getUserInventory = () => {
  return user.value?.inventory || []
}

// 添加物品到用户库存
const addItemToInventory = (item) => {
  if (!user.value) {
    throw new Error('用户未登录')
  }
  
  user.value.inventory = user.value.inventory || []
  user.value.inventory.push(item)
  saveUserToLocalStorage(user.value)
  return user.value.inventory
}

// 购买宠物用品
const buyPetSupply = (supply) => {
  if (!user.value) {
    throw new Error('用户未登录')
  }
  
  if (!supply.price || (user.value.coins || 0) < supply.price) {
    throw new Error('金币不足，无法购买')
  }
  
  // 扣除金币
  user.value.coins -= supply.price
  
  // 添加物品到库存
  user.value.inventory = user.value.inventory || []
  
  // 检查是否已经拥有该物品
  const existingItemIndex = user.value.inventory.findIndex(item => item.id === supply.id)
  if (existingItemIndex >= 0) {
    // 增加数量
    user.value.inventory[existingItemIndex].quantity = (user.value.inventory[existingItemIndex].quantity || 1) + 1
  } else {
    // 添加新物品
    user.value.inventory.push({
      ...supply,
      quantity: 1,
      purchasedAt: new Date().toISOString()
    })
  }
  
  saveUserToLocalStorage(user.value)
  return {
    success: true,
    remainingCoins: user.value.coins,
    item: user.value.inventory.find(item => item.id === supply.id)
  }
}

// 计算会员等级进度
const calculateMembershipProgress = () => {
  if (!user.value?.membership) {
    return { currentLevel: 1, nextLevel: 2, progress: 0 }
  }
  
  const { level, points } = user.value.membership
  const pointsToNextLevel = level * 100 // 每级需要的经验值递增
  const progressPercentage = Math.min((points / pointsToNextLevel) * 100, 100)
  
  return {
    currentLevel: level,
    nextLevel: level + 1,
    progress: progressPercentage,
    currentPoints: points,
    pointsToNextLevel
  }
}

// 添加会员积分
const addMembershipPoints = (points) => {
  if (!user.value) {
    throw new Error('用户未登录')
  }
  
  user.value.membership = user.value.membership || { level: 1, points: 0 }
  user.value.membership.points += points
  
  // 检查是否可以升级
  const pointsToNextLevel = user.value.membership.level * 100
  while (user.value.membership.points >= pointsToNextLevel) {
    user.value.membership.points -= pointsToNextLevel
    user.value.membership.level += 1
    // 升级奖励
    user.value.coins += 100 // 每升一级奖励100金币
  }
  
  saveUserToLocalStorage(user.value)
  return user.value.membership
}

// 导出组合式函数
export const useAuth = () => {
  return {
    // 状态
    user,
    isAuthenticated,
    isLoading,
    
    // 方法
    initializeAuth,
    login,
    register,
    logout,
    getUserCoins,
    addCoins,
    spendCoins,
    getUserInventory,
    addItemToInventory,
    buyPetSupply,
    calculateMembershipProgress,
    addMembershipPoints,
    
    // 计算属性
    membershipProgress: computed(() => calculateMembershipProgress())
  }
}